//
//  ZH_ShoppingCarViewController.m
//  WisdomStar
//
//  Created by zhangliwen on 2018/11/12.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "ZH_ShoppingCarViewController.h"
#import "GC_DetailSegmentView.h"
#import "ZH_ClassViewModel.h"
#import "ZH_ShopCarTableViewCell.h"
#import "ZH_StudentListModel.h"
#import "ZH_ConfirmOrdrViewController.h"
@interface ZH_ShoppingCarViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,weak)UIView *topView;
@property (nonatomic, strong) GC_DetailSegmentView *detailsSegmentView;
@property (nonatomic,weak)UITableView *tableView;
///详情选择
@property (nonatomic, assign) NSInteger detailsCurrentItem;
///底部View
@property (nonatomic, weak) UIView *bottomView;
///全选
@property (nonatomic, weak) UIButton *allButton;
///合计
@property (nonatomic, weak) UILabel *totalLabel;
///删除
@property (nonatomic, weak) UIButton *deleteButton;
//viewModel
@property (nonatomic, strong)ZH_ClassViewModel *viewModel;
@property (nonatomic,assign)NSInteger index;
@property (nonatomic,strong)NSMutableArray *cids;
@end

@implementation ZH_ShoppingCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUserInterface];
    [self initData];
}
- (void)cleanUpData{
    [self setViewModel:nil];
}
///更新导航栏显示
- (void)loadNavigationBarBackground{
    [((Hen_BaseNavigationViewController*)self.navigationController) setNavigationBarBgColor:[UIColor clearColor]];
    [((Hen_BaseNavigationViewController*)self.navigationController) setBackgroundHidden:YES];
    [((Hen_BaseNavigationViewController*)self.navigationController) setShadowViewHidden:YES];
    [self.navigationController.navigationBar setTintColor:kFontColorWhite];
    [((Hen_BaseNavigationViewController*)self.navigationController) setNavigationBarTitleColor:kFontColorWhite];
}
- (void)initData{
    if (self.detailsCurrentItem == 0) {
        WEAKSelf;
        [self.viewModel studentListResultBlock:^(NSString *code, NSString *message, id data) {
            if ([code isEqualToString:@"0"]) {
                [weakSelf setNumGoodsPrice];
                [weakSelf.tableView reloadData];
            }
            else{
                if ([code isEqualToString:@"1002"]) {
                    [self showHint:@"登录过期"];
                }
                else{
                    [weakSelf showHint:message];
                }
            }
        }];
    }
}
- (void)initUserInterface{
    self.navigationItem.title = @"购物车";
    self.view.backgroundColor = kCommonBackgroudColor;
   
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 40, 40);
    btn.adjustsImageWhenHighlighted = NO;
    [btn setTitle:@"编辑" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(edite:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *editeItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = editeItem;
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(-[DATAMODEL KNavigationBarHeioght]);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(FITSCALE(102));
    }];
    [self.view addSubview:self.detailsSegmentView];
    [self.detailsSegmentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom).offset(FITSCALE(-15));
        make.left.equalTo(self.view).offset(FITSCALE(40));
        make.right.equalTo(self.view).offset(FITSCALE(-40));
        make.height.mas_equalTo(FITSCALE(41));
    }];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.mas_equalTo(HEIGHT_TRANSFORMATION(98));
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.detailsSegmentView.mas_bottom).offset(FITSCALE(9));
        make.left.equalTo(self.view).offset(FITSCALE(12));
        make.right.equalTo(self.view).offset(FITSCALE(-12));
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
}
-(void)edite:(UIButton*)edite{
    if (edite.selected) {
        edite.selected = NO;
        [self.deleteButton setTitle:@"结算" forState:UIControlStateNormal];
        self.totalLabel.hidden = NO;
//        self.priceLabel.hidden = YES;
    }
    else{
        edite.selected = YES;
        [self.deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        self.totalLabel.hidden = YES;
//        self.priceLabel.hidden = YES;
    }
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.detailsCurrentItem == 0) {
        return self.viewModel.studentListArray.count;
    }
    else if (self.detailsCurrentItem == 1){
        return 0;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.detailsCurrentItem == 0) {
        ZH_ShopCarTableViewCell *cell = [ZH_ShopCarTableViewCell cellWithTableView:tableView];
        [cell updataUI:self.viewModel.studentListArray[indexPath.row]];
        WEAKSelf;
        cell.onCheckboxBlock = ^(BOOL isSelected) {
            [weakSelf onButton:indexPath.row andGid:isSelected];
        };
        return cell;
    }
    return nil;
}
- (void)onButton:(NSInteger)index andGid:(BOOL)isbool{
    ZH_StudentListModel *model = [[ZH_StudentListModel alloc] init];
    model = self.viewModel.studentListArray[index];
    model.isSelected = isbool;
    [self.viewModel.studentListArray replaceObjectAtIndex:index withObject:model];
    [self setNumGoodsPrice];
    [self.tableView reloadData];
    NSInteger indexs = 0;
    for (ZH_StudentListModel *model in self.viewModel.studentListArray) {
        if (model.isSelected) {
            indexs ++;
        }
    }
    if (indexs == self.viewModel.studentListArray.count) {
        self.allButton.selected = YES;
    }
    else{
        self.allButton.selected = NO;
    }
    [self.tableView reloadData];
}
- (void)onAllButtonBlock:(UIButton *)sender{
    if(sender.isSelected){
        [sender setSelected:NO];
    }else{
        [sender setSelected:YES];
    }
    [self checkBoxAllShopAndGoodsWithItem:sender.isSelected];
}
- (void)setNumGoodsPrice{
    double totalPrice = 0;
    for (ZH_StudentListModel *model in self.viewModel.studentListArray) {
        if (model.isSelected) {
            totalPrice = totalPrice + [model.price doubleValue];
        }
        self.totalLabel.text = [NSString stringWithFormat:@"%.2lf",totalPrice];
    }
}
- (void)checkBoxAllShopAndGoodsWithItem:(BOOL)item{
    for (ZH_StudentListModel *model in self.viewModel.studentListArray) {
        model.isSelected = item;
    }
    [self setNumGoodsPrice];
    [self.tableView reloadData];
    
}
- (void)onDeleteBlock:(UIButton *)button{
    NSMutableArray *models = [NSMutableArray array];
    if ([self.deleteButton.titleLabel.text isEqualToString:@"结算"] ) {
        [self.cids removeAllObjects];
        for (ZH_StudentListModel *model in self.viewModel.studentListArray) {
            if (model.isSelected) {
                [self.cids addObject:@(model.course_id)];
                [models addObject:model];
            }
        }
        NSString *cids = [self.cids componentsJoinedByString:@","];
        if (cids.length > 0) {
            [self.viewModel.submitParam setObject:cids forKey:@"course_id"];
            WEAKSelf;
            [self.viewModel submitResultBlock:^(NSString *code, NSString *message, id data) {
                if ([code isEqualToString:@"0"]) {
                    ZH_ConfirmOrdrViewController *vc = [[ZH_ConfirmOrdrViewController alloc] init];
                    vc.totlePrice = self.totalLabel.text;
                    vc.models = models;
                    vc.hidesBottomBarWhenPushed = YES;
                    vc.sign = data[@"data"][@"sign"];
                    vc.trade = data[@"data"][@"trade_no"];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                else{
                    [weakSelf showHint:message];
                }
            }];
        }
        else{
            [self showHint:@"请选择你要购买的商品"];
        }
    }
    else{
        [self.cids removeAllObjects];
        for (ZH_StudentListModel *model in self.viewModel.studentListArray) {
            if (model.isSelected) {
                [self.cids addObject:@(model.course_id)];
            }
        }
        
        NSString *cids = [self.cids componentsJoinedByString:@","];
        if (cids.length > 0) {
            [self.viewModel.deletCarParam setObject:cids forKey:@"course_id"];
            WEAKSelf;
            [self.viewModel deleteCarResultBlock:^(NSString *code, NSString *message, id data) {
                
                if ([code isEqualToString:@"0"]) {
                    self.allButton.selected = NO;
                    [self initData];
                    [weakSelf.tableView reloadData];
                }
                else{
                    [weakSelf showHint:message];
                }
            }];

        }
        else{
            [self showHint:@"请选择你要移除的订单"];
        }
        if (self.cids.count == self.viewModel.studentListArray.count) {
            [self.viewModel.studentListArray removeAllObjects];
        }
    }
}
#pragma mark - getter,setter
///图文 产品 选择
- (GC_DetailSegmentView *)detailsSegmentView
{
    if(!_detailsSegmentView){
        _detailsSegmentView = [[GC_DetailSegmentView alloc] initWithHeight:FITSCALE(41)];
        [_detailsSegmentView setItems:@[@"课程",@"商品"]];
        [_detailsSegmentView setBottomLineImageViewHidden:NO];
        [_detailsSegmentView setSelectItem:0];
        self.detailsCurrentItem = 0;
        WEAKSelf;
        _detailsSegmentView.onSelectedBlock = ^(NSInteger item) {
            if(item == 0){
                weakSelf.detailsCurrentItem = item;
                [weakSelf.tableView reloadData];
                
            }else if(item == 1){
                weakSelf.detailsCurrentItem = item;
                
                [weakSelf.tableView reloadData];
            }
            
        };
    }
    return _detailsSegmentView;
}
- (UITableView *)tableView{
    if(!_tableView){
        UITableView *tableView = [UITableView createTableViewWithDelegateTarget:self];
        tableView.backgroundColor = kCommonBackgroudColor;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView setCellAutoAdaptationForEstimatedRowHeight:FITHEIGHT(100)];
        [self.view addSubview:_tableView = tableView];
    }
    return _tableView;
}
- (UIView *)bottomView
{
    if(!_bottomView){
        UIView *view = [UIView createViewWithBackgroundColor:kCommonWhiteBg];
        
        [self.view addSubview:_bottomView = view];
        
        UIImageView *lineImageView = [UIImageView createImageViewWithName:@""];
        [view addSubview:lineImageView];
        
        [lineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(view);
            make.top.equalTo(view);
        }];
        //全选
        UIButton *allButton = [UIButton createButtonWithTitle:@" 全选" normalImage:@"icon_sure" pressImage:@"icon_sure_selected" target:self action:@selector(onAllButtonBlock:)];
        [view addSubview:_allButton = allButton];
        [allButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view);
            make.height.equalTo(view);
            make.centerY.equalTo(view);
            make.width.mas_equalTo(FITSCALE(190/2));
        }];
        UILabel *label = [UILabel createLabelWithText:@"¥0.00" font:kFontSize_26];
        label.textColor = [UIColor colorWithHexString:@"#E32D2C"];
        [view addSubview:_totalLabel = label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(view);
            make.left.equalTo(self.allButton.mas_right).offset(FITSCALE(12));
        }];
        ///删除按钮
        UIButton *deleteButton = [UIButton createButtonWithTitle:@"结算" backgroundNormalImage:@"" backgroundPressImage:@"" target:self action:@selector(onDeleteBlock:)];
        deleteButton.backgroundColor = [UIColor colorWithHexString:@"#00C9AE"];
        deleteButton.titleLabel.font = kFontSize_28;
        [deleteButton setTitleClor:kFontColorWhite];
        [view addSubview:_deleteButton = deleteButton];
        [deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view);
            make.centerY.equalTo(view);
            make.width.mas_equalTo((kMainScreenWidth - FITSCALE(190/2))/2);
            make.height.mas_equalTo(view);
        }];
        
    }
    return _bottomView;
}
- (ZH_ClassViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[ZH_ClassViewModel alloc] init];
    }
    return _viewModel;
}
-(NSMutableArray *)cids{
    if (_cids == nil) {
        _cids = [NSMutableArray array];
    }
    return _cids;
}
- (UIView *)topView{
    if (!_topView) {
        UIView *view = [UIView createViewWithBackgroundColor:[UIColor colorWithHexString:@"#00C9AE"]];
        [self.view addSubview:_topView = view];
    }
    return _topView ;
}
@end
